import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:${USER}
 * Date:${YEAR}-${MONTH}-${DAY}
 * ${TIME}
 */
public class Main {
    int[] dx={0,0,-1,1};
    int[] dy={1,-1,0,0};
    int m,n;
    public int[][] updateMatrix(int[][] mat) {
        m=mat.length;n=mat[0].length;
        Queue<int[]> queue=new LinkedList<>();
        boolean[][] vis=new boolean[m][n];
        int[][] dist=new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(mat[i][j]==0){
                    vis[i][j]=true;
                    queue.add(new int[]{i,j});
                }
            }
        }
        while (!queue.isEmpty()){
            int size= queue.size();
            while (size-->0){
                int[] tmp= queue.poll();
                int a=tmp[0];int b=tmp[1];
                for (int i = 0; i < 4; i++) {
                    int x=a+dx[i];int y=b+dy[i];
                    if(x>=0&&x<m&&y>=0&&y<n&&vis[x][y]==false&&mat[x][y]!=0){
                        dist[x][y]=dist[a][b]+1;
                        queue.add(new int[]{x,y});
                        vis[x][y]=true;
                    }
                }
            }
        }
        return dist;
    }
}